<?php

namespace App\Providers;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        if (config('common.write_sql_log')) {
            $this->writeSqlLog();
        }
    }

    /**
     * FunctionName：writeSqlLog
     * Description：将 sql 语句 写入 log
     * Author：lwl
     */
    private function writeSqlLog()
    {
        DB::listen(
            function ($sql) {
                $sql = $sql->sql;
                $logInstance = Log::channel('query_log');
                $logInstance->info(PHP_EOL);
                $logInstance->info('---------------------------------------- 响应 START ------------------------------');
                $logInstance->info('请求唯一标识:' . uuid());
                $logInstance->info('请求地址:' . request()->getPathInfo());
                $logInstance->info('语句:' . $sql);
                $consuming = microtime(true) - LARAVEL_START;
                $logInstance->info('语句耗时:' . $consuming . '秒');
                $logInstance->info('PHP占用内存:' . memory_get_peak_usage(true) / 1024 / 1024 . 'MB');
                $logInstance->info('---------------------------------------- 响应 END ---------------------------------');
            }
        );
    }
}
